<template>
  <div class="statistics-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2>
            <el-icon><DataAnalysis /></el-icon>
            {{ $t('workReports.layout.tabs.statistics') }}
          </h2>
          <p>{{ $t('workReports.statistics.subtitle') }}</p>
        </div>
        <div class="action-section">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            :range-separator="$t('workReports.statistics.dateRange.separator')"
            :start-placeholder="$t('workReports.statistics.dateRange.startDate')"
            :end-placeholder="$t('workReports.statistics.dateRange.endDate')"
            style="width: 240px"
            @change="handleDateRangeChange"
          />
          <el-button type="primary" @click="refreshData" :loading="loading">
            <el-icon><Refresh /></el-icon>
            {{ $t('workReports.statistics.refreshData') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计概览卡片 -->
    <div class="overview-cards">
      <el-card class="overview-card" shadow="hover">
        <div class="card-content">
          <div class="card-icon total">
            <el-icon><Document /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ reportStats?.totalReports || 0 }}</div>
            <div class="card-label">{{ $t('workReports.statistics.overview.totalReports') }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="overview-card" shadow="hover">
        <div class="card-content">
          <div class="card-icon daily">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ reportStats?.typeStats?.DAILY || 0 }}</div>
            <div class="card-label">{{ $t('workReports.statistics.overview.dailyReports') }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="overview-card" shadow="hover">
        <div class="card-content">
          <div class="card-icon weekly">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ reportStats?.typeStats?.WEEKLY || 0 }}</div>
            <div class="card-label">{{ $t('workReports.statistics.overview.weeklyReports') }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="overview-card" shadow="hover">
        <div class="card-content">
          <div class="card-icon monthly">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ reportStats?.typeStats?.MONTHLY || 0 }}</div>
            <div class="card-label">{{ $t('workReports.statistics.overview.monthlyReports') }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 第一行图表 -->
      <div class="charts-row">
        <!-- 报告类型分布饼图 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>{{ $t('workReports.statistics.charts.reportTypeDistribution') }}</h3>
              <el-button size="small" @click="exportChart('typeChart')">
                <el-icon><Download /></el-icon>
                {{ $t('workReports.statistics.actions.export') }}
              </el-button>
            </div>
          </template>
          <div ref="typeChartRef" class="chart-container" v-loading="loading"></div>
        </el-card>

        <!-- 报告状态分布饼图 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>{{ $t('workReports.statistics.charts.reportStatusDistribution') }}</h3>
              <el-button size="small" @click="exportChart('statusChart')">
                <el-icon><Download /></el-icon>
                {{ $t('workReports.statistics.actions.export') }}
              </el-button>
            </div>
          </template>
          <div ref="statusChartRef" class="chart-container" v-loading="loading"></div>
        </el-card>
      </div>

      <!-- 第二行图表 -->
      <div class="charts-row">
        <!-- 报告创建趋势折线图 -->
        <el-card class="chart-card full-width">
          <template #header>
            <div class="chart-header">
              <h3>{{ $t('workReports.statistics.charts.reportCreationTrend') }}</h3>
              <div class="chart-actions">
                <el-radio-group v-model="trendPeriod" @change="updateTrendChart">
                  <!-- {{ AURA-X: Modify - 修复Element Plus兼容性，将label改为value. Approval: 寸止(ID:fix-element-plus-radio). }} -->
                  <el-radio-button value="week">{{ $t('workReports.statistics.periods.last7Days') }}</el-radio-button>
                  <el-radio-button value="month">{{ $t('workReports.statistics.periods.last30Days') }}</el-radio-button>
                  <el-radio-button value="year">{{ $t('workReports.statistics.periods.last12Months') }}</el-radio-button>
                </el-radio-group>
                <el-button size="small" @click="exportChart('trendChart')">
                  <el-icon><Download /></el-icon>
                  {{ $t('workReports.statistics.actions.export') }}
                </el-button>
              </div>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container large" v-loading="loading"></div>
        </el-card>
      </div>

      <!-- 第三行图表 -->
      <div class="charts-row">
        <!-- 工作记录统计柱状图 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>{{ $t('workReports.statistics.charts.workRecordsStatistics') }}</h3>
              <el-button size="small" @click="exportChart('recordsChart')">
                <el-icon><Download /></el-icon>
                {{ $t('workReports.statistics.actions.export') }}
              </el-button>
            </div>
          </template>
          <div ref="recordsChartRef" class="chart-container" v-loading="loading"></div>
        </el-card>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && (!reportStats || reportStats.totalReports === 0)" class="empty-state">
      <el-icon size="64" color="#C0C4CC"><PieChart /></el-icon>
      <h3>{{ $t('workReports.statistics.emptyState.title') }}</h3>
      <p>{{ $t('workReports.statistics.emptyState.subtitle') }}</p>
      <el-button type="primary" @click="goToGenerate">
        <el-icon><Plus /></el-icon>
        {{ $t('workReports.statistics.emptyState.generateReport') }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  DataAnalysis, PieChart, Refresh, Document, Calendar,
  Download, Plus
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { useWorkReportStore } from '@/stores/workReportStore'


const router = useRouter()
const { t } = useI18n()
const workReportStore = useWorkReportStore()

// ==================== 响应式数据 ====================

const loading = ref(false)
const dateRange = ref<[Date, Date] | null>(null)
const trendPeriod = ref('week')

// 图表引用
const typeChartRef = ref<HTMLDivElement>()
const statusChartRef = ref<HTMLDivElement>()
const trendChartRef = ref<HTMLDivElement>()
const recordsChartRef = ref<HTMLDivElement>()

// 图表实例
let typeChart: echarts.ECharts | null = null
let statusChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null
let recordsChart: echarts.ECharts | null = null

// ==================== 计算属性 ====================

const reportStats = computed(() => workReportStore.reportStats)

// ==================== 方法 ====================

/**
 * 初始化页面
 */
const initPage = async () => {
  await refreshData()
  await nextTick()
  initCharts()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

/**
 * 刷新数据
 */
const refreshData = async () => {
  try {
    loading.value = true
    // 同时获取报告统计和分类统计数据
    await Promise.all([
      workReportStore.fetchReportStats(),
      workReportStore.fetchCategoryStats()
    ])
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 日期范围变化处理
 */
const handleDateRangeChange = (_dates: [Date, Date] | null) => {
  // TODO: 根据日期范围筛选数据
  refreshData()
}

/**
 * 初始化所有图表
 */
const initCharts = () => {
  initTypeChart()
  initStatusChart()
  initTrendChart()
  initRecordsChart()
}

/**
 * 更新工作记录统计图表
 */
const updateRecordsChart = () => {
  if (!recordsChart) return

  // 使用真实的工作记录分类统计数据
  const categories: string[] = []
  const data: number[] = []

  // 从分类统计数据中获取真实数据
  const categoryStatsData = workReportStore.categoryStats || {}
  if (Object.keys(categoryStatsData).length > 0) {
    // 使用真实的分类统计数据
    Object.entries(categoryStatsData).forEach(([categoryName, count]) => {
      categories.push(categoryName)
      data.push(count)
    })
  } else {
    // 如果没有统计数据，显示默认分类
    const defaultCategories = ['开发', '测试', '会议', '学习', '文档']
    defaultCategories.forEach(name => {
      categories.push(name)
      data.push(0)
    })
  }

  // 更新图表配置
  const option = {
    title: {
      text: t('workReports.statistics.charts.workRecordsStatistics'),
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: t('workReports.statistics.table.workRecords'),
        type: 'bar',
        barWidth: '60%',
        data: data,
        itemStyle: {
          borderRadius: [4, 4, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#409EFF' },
            { offset: 1, color: '#67C23A' }
          ])
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  recordsChart.setOption(option)
}

/**
 * 初始化报告类型分布饼图
 */
const initTypeChart = () => {
  if (!typeChartRef.value || !reportStats.value) return

  typeChart = echarts.init(typeChartRef.value)

  const data = [
    { value: reportStats.value.typeStats?.DAILY || 0, name: t('workReports.generate.reportTypes.daily') },
    { value: reportStats.value.typeStats?.WEEKLY || 0, name: t('workReports.generate.reportTypes.weekly') },
    { value: reportStats.value.typeStats?.MONTHLY || 0, name: t('workReports.generate.reportTypes.monthly') }
  ].filter(item => item.value > 0)

  const option = {
    title: {
      text: t('workReports.statistics.charts.reportTypeDistribution'),
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} \\n{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: t('workReports.statistics.charts.reportTypeDistribution'),
        type: 'pie',
        radius: '50%',
        center: ['50%', '60%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        }
      }
    ],
    color: ['#409EFF', '#67C23A', '#E6A23C']
  }

  typeChart.setOption(option)
}

/**
 * 初始化报告状态分布饼图
 */
const initStatusChart = () => {
  if (!statusChartRef.value || !reportStats.value) return

  statusChart = echarts.init(statusChartRef.value)

  const data = [
    { value: reportStats.value.statusStats?.DRAFT || 0, name: t('workReports.manage.statusOptions.draft') },
    { value: reportStats.value.statusStats?.FINAL || 0, name: t('workReports.manage.statusOptions.final') },
    { value: reportStats.value.statusStats?.ARCHIVED || 0, name: t('workReports.manage.statusOptions.archived') }
  ].filter(item => item.value > 0)

  const option = {
    title: {
      text: t('workReports.statistics.charts.reportStatusDistribution'),
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} \\n{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: t('workReports.statistics.charts.reportStatusDistribution'),
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '60%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        }
      }
    ],
    color: ['#909399', '#67C23A', '#E6A23C']
  }

  statusChart.setOption(option)
}

/**
 * 初始化趋势图表
 */
const initTrendChart = () => {
  if (!trendChartRef.value || !reportStats.value) return

  trendChart = echarts.init(trendChartRef.value)
  updateTrendChart()
}

/**
 * 更新趋势图表
 */
const updateTrendChart = () => {
  if (!trendChart || !reportStats.value) return

  let xAxisData: string[] = []
  let seriesData: number[] = []

  if (trendPeriod.value === 'week') {
    // 最近7天数据
    const recentTrend = reportStats.value.recentTrend || []
    xAxisData = recentTrend.map(item => formatDate(item.date))
    seriesData = recentTrend.map(item => item.count)
  } else if (trendPeriod.value === 'month') {
    // 最近30天数据 - 使用真实数据
    const recentTrend = reportStats.value.recentTrend || []
    if (recentTrend.length > 0) {
      xAxisData = recentTrend.map(item => formatDate(item.date))
      seriesData = recentTrend.map(item => item.count)
    } else {
      // 如果没有数据，显示空的30天
      const today = new Date()
      for (let i = 29; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(date.getDate() - i)
        xAxisData.push(formatDate(date.toISOString().split('T')[0]))
        seriesData.push(0)
      }
    }
  } else {
    // 最近12个月数据
    const monthlyTrend = reportStats.value.monthlyTrend || []
    xAxisData = monthlyTrend.map(item => `${item.year}-${item.month.toString().padStart(2, '0')}`)
    seriesData = monthlyTrend.map(item => item.count)
  }

  const option = {
    title: {
      text: t('workReports.statistics.charts.reportCreationTrend'),
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['报告数量'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: xAxisData
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: t('workReports.statistics.overview.totalReports'),
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          width: 3
        },
        areaStyle: {
          opacity: 0.3
        },
        emphasis: {
          focus: 'series'
        },
        data: seriesData
      }
    ],
    color: ['#409EFF']
  }

  trendChart.setOption(option)
}

/**
 * 初始化工作记录统计柱状图
 */
const initRecordsChart = () => {
  if (!recordsChartRef.value) return

  recordsChart = echarts.init(recordsChartRef.value)

  // 调用更新方法来设置图表数据
  updateRecordsChart()
}





/**
 * 导出图表
 */
const exportChart = (chartType: string) => {
  let chart: echarts.ECharts | null = null
  let fileName = ''

  switch (chartType) {
    case 'typeChart':
      chart = typeChart
      fileName = '报告类型分布图'
      break
    case 'statusChart':
      chart = statusChart
      fileName = '报告状态分布图'
      break
    case 'trendChart':
      chart = trendChart
      fileName = '报告创建趋势图'
      break
    case 'recordsChart':
      chart = recordsChart
      fileName = '工作记录统计图'
      break
  }

  if (chart) {
    const url = chart.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })

    const link = document.createElement('a')
    link.href = url
    link.download = `${fileName}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('图表导出成功')
  }
}



/**
 * 窗口大小变化处理
 */
const handleResize = () => {
  typeChart?.resize()
  statusChart?.resize()
  trendChart?.resize()
  recordsChart?.resize()
}



/**
 * 跳转到生成报告页面
 */
const goToGenerate = () => {
  router.push({ name: 'ReportGenerate' })
}

// ==================== 工具方法 ====================

/**
 * 格式化日期显示
 */
const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
}



// ==================== 生命周期 ====================

onMounted(() => {
  initPage()
})

onUnmounted(() => {
  // 销毁图表实例
  typeChart?.dispose()
  statusChart?.dispose()
  trendChart?.dispose()
  recordsChart?.dispose()

  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})

// ==================== 监听器 ====================

// 监听分类统计数据变化，更新工作记录统计图表
watch(() => workReportStore.categoryStats, () => {
  if (recordsChart) {
    updateRecordsChart()
  }
}, { deep: true })

</script>

<style scoped lang="scss">
.statistics-view {
  background-color: var(--el-bg-color-page);
}

// 页面头部
.page-header {
  margin-bottom: 20px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .title-section {
      h2 {
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 24px;
        color: var(--el-text-color-primary);
        font-weight: 600;
      }

      p {
        margin: 0;
        color: var(--el-text-color-regular);
        font-size: 14px;
      }
    }

    .action-section {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }
}

// 统计概览卡片
.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;

  .overview-card {
    .card-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .card-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;

        &.total {
          background: linear-gradient(135deg, #409EFF, #67C23A);
        }

        &.daily {
          background: linear-gradient(135deg, #409EFF, #409EFF);
        }

        &.weekly {
          background: linear-gradient(135deg, #67C23A, #67C23A);
        }

        &.monthly {
          background: linear-gradient(135deg, #E6A23C, #E6A23C);
        }
      }

      .card-info {
        flex: 1;

        .card-value {
          font-size: 24px;
          font-weight: 600;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }

        .card-label {
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
      }
    }
  }
}

// 图表容器
.charts-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;

  .charts-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;

    &:has(.full-width) {
      grid-template-columns: 1fr;
    }
  }

  .chart-card {
    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        color: var(--el-text-color-primary);
      }

      .chart-actions {
        display: flex;
        gap: 8px;
        align-items: center;
      }
    }

    .chart-container {
      width: 100%;
      height: 300px;

      &.large {
        height: 400px;
      }
    }
  }
}

// 数据表格卡片
.data-table-card {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      color: var(--el-text-color-primary);
    }

    .table-actions {
      display: flex;
      gap: 8px;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 80px 20px;

  h3 {
    margin: 16px 0 8px 0;
    color: var(--el-text-color-primary);
    font-size: 18px;
  }

  p {
    margin: 0 0 24px 0;
    color: var(--el-text-color-regular);
    font-size: 14px;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .charts-container .charts-row {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .statistics-view {
    padding: 12px;
  }

  .page-header .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .overview-cards {
    grid-template-columns: 1fr;
  }

  .chart-card .chart-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .chart-actions {
      justify-content: center;
    }
  }

  .data-table-card .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .table-actions {
      justify-content: center;
    }
  }
}

// 图表主题适配
@media (prefers-color-scheme: dark) {
  .overview-cards .overview-card .card-content .card-icon {
    &.total {
      background: linear-gradient(135deg, #337ecc, #529b2e);
    }

    &.daily {
      background: linear-gradient(135deg, #337ecc, #337ecc);
    }

    &.weekly {
      background: linear-gradient(135deg, #529b2e, #529b2e);
    }

    &.monthly {
      background: linear-gradient(135deg, #b88230, #b88230);
    }
  }
}
</style>
